package com.cnap.config;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.cnap.CnapApplicationTests;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * <类文件描述>
 *
 * @author xc
 **/
class TokenFilterTest extends CnapApplicationTests {

    @Autowired
    private UserSysConfig userSysConfig;

    @Test
    void doFilter() throws IOException {
        TokenFilter tokenFilter = new TokenFilter(userSysConfig);
        HttpServletRequest servlet = Mockito.mock(HttpServletRequest.class);
        Map<String, Object> map = new HashMap<>();
        map.put(JWT.EXPIRES_AT, System.currentTimeMillis() + 30 * 1000);
        String jwt = JWTUtil.createToken(map, JWTSignerUtil.hs256("12345".getBytes(StandardCharsets.UTF_8)));
        Mockito.when(servlet.getHeader("Authorization")).thenReturn(jwt);

        HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
        Mockito.when(response.getWriter()).thenReturn(new PrintWriter(new ByteArrayOutputStream(100)));

        Assertions.assertDoesNotThrow(()->{
            tokenFilter.doFilter(servlet, response, Mockito.mock(FilterChain.class));
        });
    }

    @Test
    void destroy() {
        TokenFilter tokenFilter = new TokenFilter(userSysConfig);
        Assertions.assertDoesNotThrow(()->{
            tokenFilter.destroy();
        });
    }
}